package com.xxlie.auth.endpoint;

import com.xxlie.auth.domain.Setting;
import com.xxlie.auth.service.SettingService;
import com.xxlie.core.common.ValidateUtil;
import com.xxlie.core.model.View;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController("apiAdminSettingSystem")
@RequestMapping("/api/admin/setting/system/")
public class SettingEndpoint {
    @Autowired
    SettingService settingService;

    @RequestMapping("/info/{id}")
    public View info(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Long id) {
        View view = new View(20000, "获取数据成功");

        Setting setting = null;
        if (id != null) {
            setting = settingService.findOne(id);
        } else {
            setting = new Setting();
        }

        view.setData(setting);
        return view;
    }

    @RequestMapping("/list")
    public View list() {
        View view = new View(20000, "获取列表成功");

        List settingList = settingService.findAll();

        view.setData(settingList);

        return view;
    }

    @RequestMapping("/add")
    public View add(HttpServletRequest request, HttpServletResponse response, @Validated @RequestBody Setting setting, BindingResult result) {
        View view = new View(20000, "添加成功");

        if (result.hasErrors()) {
            view.setCode(40000);
            view.setMessage(ValidateUtil.first(result.getAllErrors()));
        } else {
            //检查标识是否已经添加
            Setting isExist = this.settingService.findByName(setting.getName());
            if (isExist != null) {
                return View.ofError("已经存在的设置名字，请修改");
            }

            //固定为用户自定义
            setting.setType(Setting.TYPE_CUSTOMER);

            this.settingService.save(setting);
            view.setData(setting);
        }
        return view;
    }

    @RequestMapping("/update")
    public View update(HttpServletRequest request, HttpServletResponse response, @Validated @RequestBody Setting setting, BindingResult result) {
        View view = new View(20000, "更新成功");

        if (result.hasErrors()) {
            View.ofError(ValidateUtil.first(result.getAllErrors()));
        } else {
            this.settingService.save(setting);
        }

        return view;
    }
}